<?php

class Silk_Mapi_Model_Api2_Shipping_Orders_Rest extends Silk_Mapi_Model_Api2_Shipping_Orders
{
    protected $orderId;

    protected $models;
    
    /**
     * @var Mage_Sales_Model_Order
     */
    protected $order;

    public function _retrieve()
    {
        $results = $this->getOrderInformation();
        $results['items'] = $this->getOrderItems();

        return $results ?: json_decode('{}');
    }

    public function _retrieveCollection()
    {
        $orderId = $this->getOrderId();
        $result = array();
        /** @var Mage_Sales_Model_Order_Creditmemo $creditmemo */
        $creditmemo = Mage::getModel('sales/order_creditmemo')->load($orderId, 'order_id');
        //$comment = $creditmemo->getCommentsCollection()->getFirstItem()->getComment();
        if ($creditmemo && $creditmemo->getId()) {
            $result = array(
                'increment_id' => $creditmemo->getIncrementId(),
                'grand_total' => $this->formatPrice($creditmemo->getGrandTotal()),
                'items' => $this->getCreditmemoInfo($creditmemo)
            );
        }

        return $result;
    }

    public function _create()
    {
        $images = $this->getParam('images');
        $orderId = $this->getOrderId();

        if (!$images)
            $this->_critical('上传失败，没有获取到图片!', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);

        $models = array();
        foreach ($images as $image) {
            $name = md5($image) . '.jpg';
            $path = Mage::getBaseDir() . '/media/order_credentials/order_' . $orderId;
            $image = base64_decode($image);
            if (!is_dir($path))
                mkdir($path, 0777, true);

            if (!$image)
                $this->_critical('图片数据格式不正确!', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);

            $size = file_put_contents($path . '/' . $name, $image);
            if (!$size)
                $this->_critical('图片上传失败!', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);

            $model = Mage::getModel('tms/shipping_order_credentials');
            $data = array(
                'order_id' => $orderId,
                'filename' => $name
            );
            $model->addData($data);
            $models[] = $model;
        }

        /** @var Mage_Core_Model_Resource_Transaction $transactionSave */
        $transactionSave = Mage::getModel('core/resource_transaction');
        try {
            foreach ($models as $model) {
                $transactionSave->addObject($model);
            }
            $transactionSave->save();
        } catch (Exception $e) {
            $this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }

        return array();
    }

    public function _update()
    {
        $this->canComplete();

        if ($this->_getItemQtys()) {
            $this->createInvoiceAndShipment();
        }

        if ($this->_getItemData()) {
            $this->createCreditmemo();
        }

        try {
            $this->orderComplete();
        } catch (Exception $e) {
            //$this->deleteCreditmemo();
            $this->_critical($e->getMessage(), $e->getCode());
        }

        return array();
    }


    protected function canComplete()
    {
        $order = $this->getCurrentOrder();

        if (!$order->hasInvoices()) {
            $this->_critical('订单还未打印！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }

        if (!$order->hasShipments()) {
            $this->_critical('订单配送信息不完整！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }
    }

    /**
     * @return Mage_Sales_Model_Order
     * @throws Exception
     * @throws Mage_Api2_Exception
     */
    protected function getCurrentOrder()
    {
        if (!$this->order) {
            $orderId = $this->getOrderId();
            /** @var Mage_Sales_Model_Order $order */
            $order = Mage::getModel('sales/order')->load($orderId);

            if ($order && $order->getId()) {
                $this->order = $order;
            } else {
                $this->_critical('订单不存在！', Mage_Api2_Model_Resource::ERROR_CHECKOUT_ORDER_NOT_FOUND);
            }
        }

        return $this->order;
    }

    protected function getOrderItems()
    {
        $orderId = $this->getOrderId();

        /** @var Silk_Tms_Model_Mysql4_Shipping_Order_Item_Collection $collection */
        $collection = Mage::getModel('tms/shipping_order_item')->getCollection()
            ->addFieldToFilter('order_id', array('eq' => $orderId));

        return $this->formatItemCollection($collection);
    }

    protected function formatItemCollection(Silk_Tms_Model_Mysql4_Shipping_Order_Item_Collection $collection)
    {
        $result = array();
        foreach ($collection as $item) {
            $result[] = array(
                'id' => (int) $item->getItemId(),
                'name' => $item->getName(),
                'image' => $this->getProductImage($item->getProductId()),
                'sku' => $item->getSku(),
                'price' => $this->formatPrice($item->getPrice()),
                'qty' => (int) $item->getQty(),
                'qty_refund' => (int) $item->getRefunded(),
                'row_total' => $this->formatPrice($item->getRowTotal())
            );
        }
        return $result;
    }

    protected function getOrderInformation()
    {
        $orderId = $this->getOrderId();

        $item = Mage::getModel('tms/shipping_order')->load($orderId, 'order_id');
        $statusHelper = Mage::helper('tms/status');
        $credentialsStatus = array(
            Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERED,
            Silk_Tms_Helper_Status::STATUS_ORDER_COMPLETED
        );
        if ($item && $item->getId()) {
        	
        	//add by wanglin start  查询订单状态
        	$order = Mage::getModel('sales/order')->load($orderId);
        	$order_status = $order->getStatus();
        	if($order_status != "closed"){
        		$order_status = $item->getStatus();
        	}
            $add_date = $order->getCreatedAt();
        	//应收金额:
        	$grand_total = $order->getGrandTotal();
        	$refund_total = $order->getSubtotalRefunded();
        	$moeny = $grand_total - $refund_total;
        	//add by wanglin end
        	
            return array(
                'status' => $statusHelper->getStatus($order_status),
                //'status_code' => $item->getStatus(),
            	'status_code' => $order_status,
                'store_name' => $item->getCustomerStoreName(),
                'order_id' => (int) $item->getOrderId(),
                'increment_id' => $item->getIncrementId(),
               // 'place_at' => $this->addEightHours($item->getPlaceOrderTime()),
                'place_at' => $this->addEightHours($add_date),
                'address' => $item->getCustomerAddress(),
                'order_owner' => $item->getCustomerName(),
                'mobile' => $item->getCustomerPhone(),
                'comment_text' => $item->getComment() ?: '',
                'credentials' => in_array($item->getStatus(), $credentialsStatus) ? $this->getCredentials() : array(),
                'subtotal' => $this->formatPrice($item->getSubtotal()),
                //'grand_total' => $this->formatPrice($item->getTotalPaid()),
                'grand_total' =>$moeny,
            );
        }
        $this->_critical('订单不存在！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
    }

    protected function getProductImage($productId)
    {
        /** @var Mage_Catalog_Helper_Image $imgHelper */
        $imgHelper = Mage::helper('catalog/image');
        $product = Mage::getModel('catalog/product')->load($productId);
        if ($product && $product->getId()) {
            return $imgHelper->init($product, 'small_image')->resize('250')."";
        }
        $this->_critical('商品不存在！', Mage_Api2_Model_Resource::ERROR_CATALOG_RETRIEVE_PRODUCT_NOT_FONND);
    }

    /**
     * Initialize creditmemo model instance
     *
     * @return Mage_Sales_Model_Order_Creditmemo
     */
    protected function _initCreditmemo()
    {
        $orderId = $this->getOrderId();
        $data   = $this->getRequest()->getBodyParams();;
        $order  = Mage::getModel('sales/order')->load($orderId);
        $invoice = $this->_initCredimemoInvoice($order);

        if (!$this->_canCreditmemo($order)) {
            return false;
        }

        $data['qtys'] = $this->_getItemData();;

        /** @var Mage_Sales_Model_Service_Order $service */
        $service = Mage::getModel('sales/service_order', $order);
        $creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);


        /**
         * Process back to stock flags
         */
        foreach ($creditmemo->getAllItems() as $creditmemoItem) {
            $creditmemoItem->setBackToStock(false);
        }

        $args = array('creditmemo' => $creditmemo, 'request' => $this->getRequest());
        Mage::dispatchEvent('adminhtml_sales_order_creditmemo_register_before', $args);

        return $creditmemo;
    }

    /**
     * Save creditmemo and related order, invoice in one transaction
     * @param Mage_Sales_Model_Order_Creditmemo $creditmemo
     * @return $this
     */
    protected function _saveCreditmemo($creditmemo)
    {
        $creditmemo->setSource(1);
        $creditmemo->setState(Mage_Sales_Model_Order_Creditmemo::STATE_OPEN);
        $transactionSave = Mage::getModel('core/resource_transaction')
            ->addObject($creditmemo)
            ->addObject($creditmemo->getOrder());
        if ($creditmemo->getInvoice()) {
            $transactionSave->addObject($creditmemo->getInvoice());
        }
        $transactionSave->save();

        return $this;
    }

    /**
     * Check if creditmeno can be created for order
     * @param Mage_Sales_Model_Order $order
     * @return bool
     */
    protected function _canCreditmemo($order)
    {
        /**
         * Check order existing
         */
        if (!$order->getId()) {
            return false;
        }

        /**
         * Check creditmemo create availability
         */
        if (!$order->canCreditmemo()) {
            return false;
        }
        return true;
    }

    /**
     * Get requested items qtys and return to stock flags
     */
    protected function _getItemData()
    {
        $data = $this->getParam('items');

        $qtys = array();
        if ($data) {
            foreach ($data as $item) {
                if (!$item['refund_qty']) continue;

                $qtys[$item['item_id']] = $item['refund_qty'];
            }
        }

        return $qtys;
    }

    /**
     * Get requested items qty's from request
     */
    protected function _getItemQtys()
    {
        $data = $this->getParam('items');

        $qtys = array();
        if ($data) {
            foreach ($data as $item) {
                $qtys[$item['item_id']] = $item['qty'];
            }
        }

        return $qtys;
    }

    protected function createCreditmemo()
    {
        $creditmemo = $this->_initCreditmemo();
        if ($creditmemo) {
            if (($creditmemo->getGrandTotal() <=0) && (!$creditmemo->getAllowZeroGrandTotal())) {
                $this->_critical('退款数量无效！', Mage_Api2_Model_Resource::ERROR_REFUND_AMOUNT_ERROR);
            }

            $comment = $this->getParam('comment_text');
            if ($comment) {
                $creditmemo->addComment(
                    $comment,
                    true
                );
            }

            $creditmemo->register();
            Mage::register('current_creditmemo', $creditmemo);
            $this->_saveCreditmemo($creditmemo);
            //$creditmemo->setState(Mage_Sales_Model_Order_Creditmemo::STATE_OPEN);
            //$creditmemo->save();
        } else {
            $this->_critical('该订单暂不支持退款！', Mage_Api2_Model_Resource::ERROR_ORDER_CAN_NOT_REFUND);
        }
    }

    protected function orderComplete()
    {
        $orderId = $this->getOrderId();

        $order = Mage::getModel('tms/shipping_order')->load($orderId, 'order_id');
        if ($order && $order->getId()) {
            $comment = $this->getParam('comment_text');
            $totalPaid = $order->getGrandTotal();
            $totalRefund = 0;
            $creditmemo = Mage::registry('current_creditmemo');
            if ($creditmemo) {
                $totalRefund = $creditmemo->getGrandTotal();
                $totalPaid = $totalPaid - $totalRefund;

                $this->setOrderItemRefund($creditmemo);
            }

            $order->setTotalPaid($totalPaid);
            $order->setTotalRefund($totalRefund);
            $order->setStatus(Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERED);
            if ($comment) {
                $order->setComment($comment);
            }

            $this->models[] = $order;
            $this->setOrderAppId();

            try {
                /** @var Mage_Sales_Model_Order $mageOrder */
                $mageOrder = Mage::getModel('sales/order')->load($orderId);
                $mageOrder->setStatus(Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_SHIP);

                /** @var Mage_Core_Model_Resource_Transaction $transactionSave */
                $transactionSave = Mage::getModel('core/resource_transaction');
                foreach ($this->models as $model) {
                    $transactionSave->addObject($model);
                }

                /** @var Mage_Sales_Model_Order $mageOrder */
                $mageOrder = Mage::getModel('sales/order')->load($orderId);
                if ($mageOrder->getStatus() != Mage_Sales_Model_Order::STATE_CLOSED) {
                    $mageOrder->addStatusToHistory(Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_SHIP, '订单配送完成', true);
                    $mageOrder->setStatus(Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_SHIP);
                    $transactionSave->addObject($mageOrder);
                }

                $transactionSave->save();

                $this->changeShippingStatus($order);
            } catch (Exception $e) {
                $this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }
        } else {
            $this->_critical('订单不存在！', Mage_Api2_Model_Resource::ERROR_CHECKOUT_ORDER_NOT_FOUND);
        }
    }

    protected function setOrderItemRefund($creditmemo)
    {
        foreach ($creditmemo->getAllItems() as $creditmemoItem) {
            if ($creditmemoItem->getQty() <= 0) continue;

            $item = Mage::getModel('tms/shipping_order_item')->load($creditmemoItem->getOrderItemId(), 'item_id');
            if ($item && $item->getId()) {
                $item->setRefunded($creditmemoItem->getQty());
                $this->models[] = $item;
            } else {
                $this->_critical('退款商品不存在！', Mage_Api2_Model_Resource::ERROR_CART_DELETE_PRODUCT_NOT_FOUND);
            }
        }
    }

    protected function getCreditmemoInfo($creditmemo)
    {
        $results = array();

        foreach ($creditmemo->getAllItems() as $creditmemoItem) {
            if ($creditmemoItem->getQty() <= 0) continue;

            $results[] = array(
                'name' => $creditmemoItem->getName(),
                'image' => $this->getProductImage($creditmemoItem->getProductId()),
                'sku' => $creditmemoItem->getSku(),
                'price' => $this->formatPrice($creditmemoItem->getPrice()),
                'qty' => (int) $creditmemoItem->getQty(),
                'row_total' => $this->formatPrice($creditmemoItem->getRowTotal())
            );
        }

        return $results;
    }

    protected function deleteCreditmemo()
    {
        $creditmemo = Mage::registry('current_creditmemo');
        if ($creditmemo) {
            $creditmemoModel = Mage::getModel('sales/order_creditmemo');
            $creditmemoModel->load($creditmemo->getId())->delete();
        }
    }

    protected function setOrderAppId()
    {
        $orderId = $this->getOrderId();
        $order = Mage::getModel('sales/order')->load($orderId);
        if ($order && $order->getId()) {
            $appId = $this->getRequest()->getHeader('App-Id');
            $order->setAppId($appId);
            $this->models[] = $order;
        } else {
            $this->_critical('订单不存在！', Mage_Api2_Model_Resource::ERROR_CHECKOUT_ORDER_NOT_FOUND);
        }
    }

    protected function changeShippingStatus($order)
    {
        $shippingId = $order->getShippingId();

        if ($shippingId) {
            $shipping = Mage::getModel('tms/shipping')->load($shippingId);
            if (!$shipping || !$shipping->getId())
                $this->_critical('运单不存在！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);

            $shipping->setTotalPaid($shipping->getTotalPaid() + $order->getTotalPaid());

            /** @var Silk_Tms_Model_Mysql4_Shipping_Order_Collection $collection */
            $collection = Mage::getModel('tms/shipping_order')->getCollection()
                ->addFieldToSelect('*')
                ->addFieldToFilter('shipping_id', array('eq' => $shippingId))
                ->addFieldToFilter('status', array('neq' => Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERED));

            if ($collection->getSize() <= 0) {
                $shipping->setStatus(Silk_Tms_Helper_Status::STATUS_SHIPPING_DELIVERED);
                $shipping->setCompletedAt($this->formatDateTime(time()));
            }

            $shipping->save();
        } else {
            $this->_critical('缺少参数7！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }
    }

    protected function getCredentials()
    {
        $orderId = $this->getOrderId();
        /** @var Silk_Tms_Model_Mysql4_Shipping_Order_Credentials_Collection $collection */
        $collection = Mage::getModel('tms/shipping_order_credentials')->getCollection();
        $collection = $collection->addFieldToFilter('order_id', array('eq' => $orderId));

        $results = array();
        $path = Mage::getBaseUrl('media') . 'order_credentials/order_' . $orderId;
        foreach ($collection as $item) {
            $results[] = array(
                'url' => $path . '/' . $item->getFilename(),
            );
        }

        return $results;
    }

    protected function getOrderId()
    {
        if (!$this->orderId) {
            $orderId = $this->getRequest()->getParam('id');
            if ($orderId) {
                $this->orderId = $orderId;
            } else {
                $this->_critical('缺少参数8！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }
        }

        return $this->orderId;
    }

    /**
     * Initialize invoice model instance
     *
     * @return Mage_Sales_Model_Order_Invoice
     */
    protected function _initInvoice()
    {
        $invoice = false;
        $orderId = $this->getOrderId();

        if ($orderId) {
            $order = Mage::getModel('sales/order')->load($orderId);
            /**
             * Check order existing
             */
            if (!$order->getId()) {
                return false;
            }
            /**
             * Check invoice create availability
             */
            if (!$order->canInvoice()) {
                return false;
            }
            $savedQtys = $this->_getItemQtys();
            $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($savedQtys);
            if (!$invoice->getTotalQty()) {
                Mage::throwException($this->__('Cannot create an invoice without products.'));
            }
        }

        return $invoice;
    }

    /**
     * Initialize requested invoice instance
     * @param unknown_type $order
     * @return Mage_Sales_Model_Order_Invoice
     */
    protected function _initCredimemoInvoice($order)
    {
        $invoice = Mage::registry('current_invoice')
            ->setOrder($order);
        return $invoice;
    }

    /**
     * Prepare shipment
     *
     * @param Mage_Sales_Model_Order_Invoice $invoice
     * @return Mage_Sales_Model_Order_Shipment
     */
    protected function _prepareShipment($invoice)
    {
        $savedQtys = $this->_getItemQtys();
        $shipment = Mage::getModel('sales/service_order', $invoice->getOrder())->prepareShipment($savedQtys);
        if (!$shipment->getTotalQty()) {
            return false;
        }

        $shipment->register();

        return $shipment;
    }

    protected function createInvoiceAndShipment()
    {
        try {
            $invoice = $this->_initInvoice();
            if ($invoice) {
                $invoice->register();

                Mage::register('current_invoice', $invoice);

                $shipment = $this->_prepareShipment($invoice);
                if ($shipment) {
                    Mage::register('current_shipment', $shipment);
                }

                $this->saveAllInTransaction();
            } else {
                $this->_critical('Invoice初始化失败!', Mage_Api2_Model_Resource::ERROR_INVOICE_FAILED);
            }
        } catch (Exception $e) {
            $this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_INVOICE_FAILED);
        }
    }

    protected function saveAllInTransaction()
    {
        /** @var Mage_Core_Model_Resource_Transaction $transactionSave */
        $transactionSave = Mage::getModel('core/resource_transaction');
        $invoice = Mage::registry('current_invoice');
        $shipment = Mage::registry('current_shipment');
        try {
            $transactionSave
                ->addObject($invoice)
                ->addObject($invoice->getOrder())
                ->addObject($shipment)
                ->save();
        } catch (Exception $e) {
            $this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }
    }
}